package org.example.config;

import org.example.dao.DiscussionDao;
import org.example.domain.Discussion;
import org.example.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListener;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Configuration
public class kafkaConsumer {
//    @Value("${spring.kafka.template.default-topic}")
    public static final String KAFKA_TOPIC = "springboot_flume_kafka";
    @Resource
    private DiscussionDao discussionDao;
    @Autowired
    private RedisCache redisCache;

    @KafkaListener(topics = KAFKA_TOPIC)
    public void consumerKafkaTopic(String msg){
//        msg = msg.substring(101);
        List<String> types = discussionDao.getTypes();
        String s =types.get(0);
        for (int i = 1; i < types.size(); i++) {
            s += "|" + types.get(i);
        }
        String pattern = "\\d+用户点击了讨论类型：[\\u4e00-\\u9fa5]*";

        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(msg);

        if(!m.matches()){
            //当未匹配上，表示不是想要的记录
            return;
        }
        System.out.println("=====收到的kafka主题消息是："+msg);
        System.out.println(types);
        String type = msg.substring(msg.lastIndexOf("：") + 1);
        System.out.println(type);
        String userId = msg.substring(0,msg.indexOf("用"));
        System.out.println(userId);
        if(!types.contains(type)){
            //数据库现存的讨论类型中不存在次类型
            return;
        }
        Map<String,Integer> likes = redisCache.getCacheObject(userId + "_likes");
        if(likes == null){
            //当用户第一次点击时，生成存贮相应的数据
            likes = new HashMap<>();
        }
        //更新redis中的数据
        boolean b = likes.containsKey(type);
        if(b){
            //点击过数据加一
            likes.put(type,likes.get(type) + 1);
        }else{
            //未点击过
            likes.put(type,1);
        }
        redisCache.setCacheObject(userId + "_likes",likes);


    }
}
